package org.pocketmoney.core;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

public class XMLWriter
{

	public static void writeObjects(List<XMLWritable> list, String fileName) throws IOException
	{
		List<Element> els = new LinkedList<Element>();
		for (XMLWritable obj: list)
		{
			els.add(obj.toXML());
		}
		writeElements(els, fileName);
	}
	
	public static void writeElements(List<Element> list, String fileName) throws IOException
	{
		Element root = new Element("records");
		Document doc = new Document(root);
		root.addContent(list);
		XMLOutputter out = new XMLOutputter();
		out.output(doc, new FileWriter(fileName));
	}
	
	public static Document read(String filename) throws FileNotFoundException, JDOMException, IOException
	{
		SAXBuilder builder = new SAXBuilder();
		return builder.build(new FileReader(filename));
	}
	
}
